﻿using Microsoft.AspNetCore.Http;

namespace Gentings.Saas.Sites
{
    /// <summary>
    /// 当前管理网站配置接口。
    /// </summary>
    /// <typeparam name="TSite">网站配置类型。</typeparam>
    public interface ISiteAccessor<TSite> where TSite : Site, new()
    {
        /// <summary>
        /// 获取或者设置网站Id。
        /// </summary>
        int SiteId { get; set; }

        /// <summary>
        /// 获取当前网站配置实例。
        /// </summary>
        TSite Current { get; }
    }

    /// <summary>
    /// 当前管理网站配置接口。
    /// </summary>
    /// <typeparam name="TSite">网站配置类型。</typeparam>
    public class SiteAccessor<TSite> : ISiteAccessor<TSite>
        where TSite : Site, new()
    {
        // 当前网站管理的网站Cookie存储键。
        private const string CookieKey = "SiteId";
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly ISiteManager<TSite> _siteManager;
        private readonly TSite _site;
        /// <summary>
        /// 初始化类<see cref="SiteAccessor{TSite}"/>。
        /// </summary>
        /// <param name="contextAccessor">Http上下文实例访问器实例。</param>
        /// <param name="siteManager">网站管理接口实例。</param>
        /// <param name="site">当前访问的网站接口实例。</param>
        public SiteAccessor(IHttpContextAccessor contextAccessor, ISiteManager<TSite> siteManager, TSite site)
        {
            _contextAccessor = contextAccessor;
            _siteManager = siteManager;
            _site = site;
        }

        private TSite? _current;
        /// <summary>
        /// 获取当前网站配置实例。
        /// </summary>
        public TSite Current
        {
            get
            {
                if (_current == null)
                {
                    if (_contextAccessor.HttpContext.Request.Cookies.TryGetValue(CookieKey, out var value) &&
                           int.TryParse(value, out var siteId))
                        _current = _siteManager.Find(siteId);
                    if (_current == null)
                    {
                        _current = _site;
                        SiteId = _site.Id;
                    }
                }
                return _current;
            }
        }

        /// <summary>
        /// 获取或者设置网站Id。
        /// </summary>
        public int SiteId
        {
            get => Current.Id;
            set
            {
                if (Current.Id == value) return;
                _current = null;
                var response = _contextAccessor.HttpContext.Response;
                response.Cookies.Delete(CookieKey);
                if (value > 0)
                {
                    response.Cookies.Append(CookieKey, value.ToString(), new CookieOptions
                    {
                        Expires = DateTimeOffset.UtcNow.AddDays(72),
                    });
                }
            }
        }
    }
}